package weeny.pre.io.parser;

import java.awt.geom.Point2D;
import java.util.regex.Pattern;

import prefuse.data.parser.DataParseException;
import prefuse.data.parser.DataParser;

/**
 * Handle column type: "Point2D" and "Point2D.Double"
 * 
 * @author weeny
 */
public class Point2DParser implements DataParser{
	public Class getType() {
		return Point2D.Double.class;
	}

	public boolean compatible(Class type) {
		return Point2D.class.isAssignableFrom(type);
	}
	public static final String HEAD = "Pnt";
	public static final String X = ":X=";
	public static final String Y = ":Y=";
	static Pattern split = Pattern.compile("(?:"+X+")|(?:"+Y+")");
	public String format(Object value) {
		if (value == null) {
			return "NULL";
		}
		StringBuffer sb = new StringBuffer();
		sb.append(HEAD);
		sb.append(X);sb.append(((Point2D)value).getX());
		sb.append(Y);sb.append(((Point2D)value).getY());
		return sb.toString();
	}

	public boolean canParse(String text) {
		return false;
	}

	public Object parse(String text) throws DataParseException {
		String[] tokens = split.split(text);
		if (tokens.length == 3 && tokens[0].equals(HEAD)) {
			double x = Double.parseDouble(tokens[1]);
			double y = Double.parseDouble(tokens[2]);
			return new Point2D.Double(x,y);
		}
		tokens = text.split(" ");
		if (tokens.length == 2) {
			double x = Double.parseDouble(tokens[0]);
			double y = Double.parseDouble(tokens[1]);
			return new Point2D.Double(x,y);
		}
		throw new DataParseException(text+" does not match "+split.pattern());

	}

}
